package com.krain.ddbb.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.krain.corelibrary.entity.PubImageBean;
import com.krain.corelibrary.helper.ImageHelper;
import com.krain.corelibrary.helper.imageloader.ImageLoader;
import com.krain.corelibrary.util.UIUtil;
import com.krain.corelibrary.widget.LayerMaskPopupWindow;
import com.krain.ddbb.R;
import com.krain.ddbb.adapter.AddresItemAdapter;
import com.krain.ddbb.adapter.WorkItemAdapter;
import com.krain.ddbb.base.BaseActivity;
import com.krain.ddbb.constant.Keys;
import com.krain.ddbb.entity.AppApi;
import com.krain.ddbb.entity.BaseEntity;
import com.krain.ddbb.entity.OrderDetailTypeBean;
import com.krain.ddbb.entity.PersonArdessBean;
import com.krain.ddbb.entity.UpLoadBean;
import com.krain.ddbb.entity.WorkNameBean;
import com.krain.ddbb.util.DateTimePickDialogUtil;
import com.orhanobut.logger.Logger;
import com.krain.corelibrary.util.BitmapUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.apache.http.client.ClientProtocolException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ex-kuangxiaomin101 on 2015-12-22.
 */
@EActivity(R.layout.activity_place_order)
public class PlaceOrderActivity extends BaseActivity {

    @ViewById(R.id.act_issue_task_et_need)
    EditText mEtNeed;//输入需求
    @ViewById(R.id.add_photo_rl)
    LinearLayout mAddPhotoRl;
    @ViewById(R.id.add_photo_first_row)
    LinearLayout mAddPhotoFirstRow;
    @ViewById(R.id.add_photo_second_row)
    LinearLayout mAddPhotoSecondRow;
    @ViewById(R.id.add_photo_total_ll)
    LinearLayout mAddPhotoTotalLl;
    @ViewById(R.id.act_place_rl_work)
    RelativeLayout mRlWorkType;//请选择工种
    @ViewById(R.id.act_place_et_craft)
    TextView mETWorkType;//EditText工种
    @ViewById(R.id.act_place_et_service_address)
    TextView mETAddresType;//EditText住址
    @ViewById(R.id.act_place_rl_time)
    RelativeLayout mRlWorkTime;//请选择时间
    @ViewById(R.id.act_place_et_service_time)
    TextView mEtWorkTime;//时间
    @ViewById(R.id.spinner_type)
    Spinner mWorkspinner;//请选择时间
    @ViewById(R.id.spinner_address)
    Spinner mAddresspinner;//请选择服务地点
    @ViewById(R.id.act_place_et_service_price)
    EditText mEtServicePrice;//请输入服务价格
    @ViewById(R.id.act_place_rl_addres)
    RelativeLayout rl_adress;


    private List<View> mPhotoViewList = new ArrayList<View>();
    //图片上传的list
    private List<View> mAddPhotoAndVideoIconList = new ArrayList<View>();
    private List<View> mTotalViewList = new ArrayList<View>();
    //拍照的存储文件
    private File cameralFile;
    // 室内图拍照的存储文件
    private File indoorImgCameralFile;
    public static final int TAKE_PHOTO_CODE = 201;
    public static final int CHOOSE_PHOTO_CODE = 200;
    public static final int MAX_PHOTO_NUM = 3;
    public static final int ADD_ADDRES_WIN = 202;
    private int mCurrentPhotoNum = 0;
    public static final int TAKE_CERTIFICATE_CODE = 205;
    public static final int TAKE_BILLS_CODE = 207;
    LayerMaskPopupWindow mPhotoPopupWindow;
    private int mPhotoWidth;
    private String str;
    ImageLoader mImageLoader;
    private WorkNameBean[] String;
    private String initStartDateTime = str; // 初始化开始时间
    private String initEndDateTime = str; // 初始化结束时间
    boolean select = true;
    private ArrayList<File> lists = new ArrayList<>();
    private int workId;
    private int addresId;


    @AfterViews
    void afterView() {
        initFirstRow();
        getWorkType(String);
        getTime();
        mEtWorkTime.setText(initStartDateTime);
        mEtServicePrice.setInputType(EditorInfo.TYPE_CLASS_PHONE);
    }

    @Click(R.id.add_photo_rl)
    void addPhotoClicked() {
        ShowPickDialog(TAKE_PHOTO_CODE, CHOOSE_PHOTO_CODE, MAX_PHOTO_NUM - mCurrentPhotoNum);
    }

    DateTimePickDialogUtil dateTimePicKDialog;

    @Click(R.id.act_place_rl_time)
//请选择服务时间
    void selectWorkTime() {
        dateTimePicKDialog = new DateTimePickDialogUtil(
                PlaceOrderActivity.this, initEndDateTime);
        dateTimePicKDialog.dateTimePicKDialog(mEtWorkTime);
    }

    @Click(R.id.act_submit_order)
    void clickToLogin() {
        showProgressDialog();
        if (verifyConditions()) {
            if (!lists.isEmpty())
                uploadPhotoToserver(lists);
            else postOrder();
        }
    }

    PersonArdessBean[] string1;

    /**
     * 得到工种列表
     *
     * @param String
     */
    @Background
    protected void getWorkType(WorkNameBean[] String) {
        OrderDetailTypeBean bean = AppApi.getsInstance(mContext).getWorktype(app.getmUserinfo().getAccess_token());
        if (bean != null) {
            WorkNameBean[] string = new WorkNameBean[bean.getWork_type().size()];
            bean.getWork_type().toArray(string);
            setAdapter(string, mWorkspinner);
            PersonArdessBean[] string1 = new PersonArdessBean[bean.getAddress().size()];
            if (string1 == null || (string1 != null && string1.length == 0)) {
                rl_adress.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivityForResult(new Intent(PlaceOrderActivity.this, AddAddresActivity_.class), ADD_ADDRES_WIN);
                    }
                });
                setAddressSpinnerVisible(View.GONE);
            } else {
                setAddressSpinnerVisible(View.VISIBLE);
                bean.getAddress().toArray(string1);
                setAdapter(string1, mAddresspinner);
            }

        }
    }

    @UiThread
    void setAddressSpinnerVisible(int visible) {
        mAddresspinner.setVisibility(visible);
    }

    @UiThread
    protected void setAdapter(final WorkNameBean[] String, Spinner mWorkspinner) {
        final WorkItemAdapter adapter = new WorkItemAdapter(PlaceOrderActivity.this, String);
        mWorkspinner.setAdapter(adapter);
        mWorkspinner.setPrompt("请选择工种");
        mWorkspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (select) {
                    //第一次初始化spinner时，不显示默认被选择的第一项即可
                    view.setVisibility(View.GONE);
                    mETWorkType.setVisibility(View.VISIBLE);

                }
                view.setVisibility(View.VISIBLE);
                mETWorkType.setVisibility(View.GONE);
                WorkNameBean bean = (WorkNameBean) adapter.getItem(position);
                workId = Integer.parseInt(bean.getId());
                select = false;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @UiThread
    protected void setAdapter(PersonArdessBean[] String, Spinner mAddresspinner) {
        final AddresItemAdapter adapter = new AddresItemAdapter(PlaceOrderActivity.this, String);
        mAddresspinner.setAdapter(adapter);
        mAddresspinner.setPrompt("请选择住址");
        mAddresspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (select) {
                    //第一次初始化spinner时，不显示默认被选择的第一项即可
                    view.setVisibility(View.GONE);
                    mETAddresType.setVisibility(View.VISIBLE);
                }
                view.setVisibility(View.VISIBLE);
                mETAddresType.setVisibility(View.GONE);
                PersonArdessBean bean = (PersonArdessBean) adapter.getItem(position);
                addresId = bean.getId();
                select = false;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 获取系统时间
     */
    private void getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        str = formatter.format(curDate);
    }

    /**
     * 检查输入
     *
     * @return
     */
    private boolean verifyConditions() {
        if (TextUtils.isEmpty(mEtNeed.getText())) {
            baseUtil.showSnackBar(this, "请输入您的需求！");
            return false;
        }
        if (TextUtils.isEmpty(mEtServicePrice.getText())) {
            baseUtil.showSnackBar(this, "请输入服务价格！");
            return false;
        }

        return true;
    }

    private void initFirstRow() {
        mPhotoWidth = (UIUtil.getWindowWidth(this) - UIUtil.dip2px(this, 40)) / 3;
        ViewGroup.LayoutParams params = mAddPhotoRl.getLayoutParams();
        params.width = mPhotoWidth;
        mAddPhotoRl.setLayoutParams(params);
        mAddPhotoAndVideoIconList.add(mAddPhotoRl);
    }

    /**
     * 选择图片方式对话框
     */
    private void ShowPickDialog(final int cameralRequstCode, final int albumReqestCode, final int selectNum) {
        View view = View.inflate(getApplicationContext(), R.layout.popup_menu_add_photo, null);
        TextView takePhoto = (TextView) view.findViewById(R.id.take_photo_tv);
        TextView choosePhoto = (TextView) view.findViewById(R.id.choose_photo_tv);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoPopupWindow.dismiss();
                String filePath = null;
                filePath = getSystemPhotoPath();
                if (filePath != null) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameralRequstCode == TAKE_CERTIFICATE_CODE) {
                        cameralFile = new File(filePath, System.nanoTime() + ".jpg");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameralFile));
                    }
                    if (cameralRequstCode == TAKE_BILLS_CODE) {
                        cameralFile = new File(filePath, System.nanoTime() + ".jpg");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameralFile));
                    }
                    if (cameralRequstCode == TAKE_PHOTO_CODE) {
                        indoorImgCameralFile = new File(filePath, System.nanoTime() + ".jpg");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(indoorImgCameralFile));
                    }
                    startActivityForResult(intent, cameralRequstCode);
                } else {
                    baseUtil.showSnackBar(PlaceOrderActivity.this, "当前无SD卡,无法使用拍照");
                }
            }
        });
        choosePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoPopupWindow.dismiss();
                Intent intent = new Intent(PlaceOrderActivity.this,
                        com.krain.ddbb.activity.MultipleAlbumActivity_.class);
                intent.putExtra(MultipleAlbumActivity.MAX_SELECTED_NUM_KEY, selectNum);
                startActivityForResult(intent, albumReqestCode);
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoPopupWindow.dismiss();
            }
        });

        if (mPhotoPopupWindow == null) {
            mPhotoPopupWindow = new LayerMaskPopupWindow(this);
            mPhotoPopupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            mPhotoPopupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            mPhotoPopupWindow.setFocusable(true);
            mPhotoPopupWindow.setOutsideTouchable(true);
        }
        mPhotoPopupWindow.setContentView(view);
        mPhotoPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

    }

    private String getSystemPhotoPath() {
        String pathSaveParent = null;
        try {
            pathSaveParent = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                    .getAbsolutePath();
        } catch (Exception e) {
            baseUtil.showSnackBar(this, "当前系统相册路径不可用,添加失败");
        }
        return pathSaveParent;
    }

    private void reCalculateWidth(View view) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mPhotoWidth, ViewGroup.LayoutParams.MATCH_PARENT);
        params.setMargins(0, 0, UIUtil.dip2px(this, 10), 0);
        view.setLayoutParams(params);
    }

    private void handleTakePhoto() {
        compressIndoorImgFile();
    }

    /**
     * 压缩图片
     */
    @Background(id = "savebitMap")
    void compressIndoorImgFile() {
        try {
            if (indoorImgCameralFile != null && indoorImgCameralFile.exists()) {
                ImageHelper imageHelper = ImageHelper.getInstance(this);
                try {
                    String cachePath = saveCompressBitmap(indoorImgCameralFile.getAbsolutePath(), imageHelper);
                    updateIndoorImage(cachePath);
                } catch (Exception e) {
                    baseUtil.showSnackBar(this, "压缩图片失败！");
                }
            }
        } catch (Exception e) {
            baseUtil.showSnackBar(this, "当前系统相册路径不可用,添加失败");
        }
        indoorImgCameralFile = null;
    }

    /**
     * 保存图片
     *
     * @param path
     * @param imageHelper
     * @return
     * @throws org.apache.http.client.ClientProtocolException
     * @throws java.io.IOException
     * @throws java.io.FileNotFoundException
     */
    private String saveCompressBitmap(String path, ImageHelper imageHelper) throws ClientProtocolException,
            IOException, FileNotFoundException {
        int degree = BitmapUtils.getBitmapDegree(path);
        Bitmap bitmap = imageHelper.loadImage(path, MultipleAlbumActivity.DEFAULT_WIDTH, MultipleAlbumActivity.DEFAULT_HEIGHT);
        if (degree != 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(degree);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }

        String parentPath = TakePicByCameralActivity.getImageCheDir(this);
        String pathCache = parentPath + System.nanoTime() + ".jpg";
        File fileCache = new File(pathCache);
        File pf = fileCache.getParentFile();
        if (pf != null) {
            pf.mkdirs();
        }
        if (!fileCache.exists()) {
            fileCache.createNewFile();
        }
        imageHelper.writeToFile(bitmap, Bitmap.CompressFormat.JPEG, MultipleAlbumActivity.COMPRESS_QAUILTY, fileCache);
        if (bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }
        return pathCache;
    }


    List<UpLoadBean> listImage = new ArrayList<>();

    // 上传图片到服务器
    @Background(id = "uploadFile")
    void uploadPhotoToserver(ArrayList<File> files) {
        listImage = AppApi.getsInstance(mContext).postFiles(app.getmUserinfo().getAccess_token(), files);
        if (listImage != null) {
            postOrder();
        }
    }

    // 发布订单
    @Background(id = "uploadFile")
    void postOrder() {
        BaseEntity result = AppApi.getsInstance(mContext).postOrder(app.getmUserinfo().getAccess_token(), workId, mEtWorkTime.getText().toString(),
                mEtServicePrice.getText().toString(), addresId,
                listImage, mEtNeed.getText().toString());
        dismissProgressDialog();
        if (result != null) {
            baseUtil.showToast(this, "发布订单成功！", Gravity.CENTER);
            finish();
        }
    }


    @UiThread
    void updateIndoorImage(final String cachePath) {
        final View view = View.inflate(PlaceOrderActivity.this, R.layout.item_photo_with_close, null);
        view.setTag("photo");
        reCalculateWidth(view);
        mPhotoViewList.add(0, view);
        ImageView indoorIv = (ImageView) view.findViewById(R.id.indoor_photo_iv);
        mImageLoader.getInstance(mContext).loadImage(PlaceOrderActivity.this, indoorIv, cachePath);
        ImageView closeTv = (ImageView) view.findViewById(R.id.close_img_iv);
        closeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoViewList.remove(view);
                mCurrentPhotoNum -= 1;
                List<File> files = new ArrayList<File>(lists);
                for (File f : files) {
                    if (f.getPath().equals(cachePath)) {
                        lists.remove(f);
                    }
                }
                files = null;
                refreshGallery();
            }
        });
        mCurrentPhotoNum += 1;
        lists.add(new File(cachePath));
        refreshGallery();
    }

    private void handleChoosePhoto(Intent data) {
        if (data != null) {
            ArrayList<String> dataList = data.getStringArrayListExtra(Keys.FILE_PATH_KEY);
            if (dataList != null && dataList.size() > 0) {
                Logger.v("图片地址为：", dataList);
                for (final String imgUrl : dataList) {
                    final View view = View.inflate(PlaceOrderActivity.this, R.layout.item_photo_with_close, null);
                    view.setTag("photo");
                    reCalculateWidth(view);
                    mPhotoViewList.add(0, view);
                    ImageView indoorIv = (ImageView) view.findViewById(R.id.indoor_photo_iv);
                    mImageLoader.getInstance(mContext).loadImage(PlaceOrderActivity.this, indoorIv, imgUrl);
                    ImageView closeTv = (ImageView) view.findViewById(R.id.close_img_iv);
                    closeTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mPhotoViewList.remove(view);
                            mCurrentPhotoNum -= 1;
                            List<File> list = new ArrayList<File>(lists);
                            for (File f : list) {
                                if (f.getPath().equals(imgUrl)) {
                                    lists.remove(f);
                                }
                            }
                            list = null;
                            refreshGallery();
                        }
                    });
                    PubImageBean bean = new PubImageBean();
                    bean.setsOriginImageUrl(imgUrl);
                    lists.add(new File(imgUrl));
                    mCurrentPhotoNum += 1;
                    refreshGallery();
                }
            }
        }
    }


    private void refreshGallery() {
        if (mCurrentPhotoNum == MAX_PHOTO_NUM) {
            //当前照片已达最大值不需要添加照片的icon
            mAddPhotoAndVideoIconList.remove(mAddPhotoRl);
        } else {
            if (!mAddPhotoAndVideoIconList.contains(mAddPhotoRl)) {
                //照片不达最大值的情况下如果没有添加照片的Icon需要添加进去
                mAddPhotoAndVideoIconList.add(mAddPhotoRl);
            }
        }
        mAddPhotoFirstRow.removeAllViews();
        mAddPhotoSecondRow.removeAllViews();
        mAddPhotoTotalLl.removeView(mAddPhotoSecondRow);

        mTotalViewList.clear();
        mTotalViewList.addAll(mPhotoViewList);
        mTotalViewList.addAll(mAddPhotoAndVideoIconList);

        for (View view : mTotalViewList) {
            if (mAddPhotoFirstRow.getChildCount() < 3) {
                mAddPhotoFirstRow.addView(view);
            } else {
                if (mAddPhotoTotalLl.getChildCount() == 1) {
                    mAddPhotoTotalLl.addView(mAddPhotoSecondRow);
                    mAddPhotoSecondRow.setVisibility(View.VISIBLE);
                }
                mAddPhotoSecondRow.addView(view);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CHOOSE_PHOTO_CODE:
                    handleChoosePhoto(data);
                    break;
                case TAKE_PHOTO_CODE:
                    handleTakePhoto();
                    break;
                case ADD_ADDRES_WIN:
                    getWorkType(String);
                    break;
                default:
                    break;
            }
        }
    }

    public static void jumpTothisActivity(BaseActivity activity) {
        Intent intent = new Intent(activity, PlaceOrderActivity_.class);
        activity.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return "下单";
    }
}
